﻿using Newtonsoft.Json;
using MySql.Data.MySqlClient;
using System.Data;
using System.Text;
using Microsoft.EntityFrameworkCore;
using Pomelo.EntityFrameworkCore.MySql;
using MySql.Data;
using System.Data;


var builder = WebApplication.CreateBuilder(args);
builder.Services.AddDbContext<LeansoftContext>(
    options => options.UseMySql(builder.Configuration.GetConnectionString("leansoftxConnection"),new MySqlServerVersion(new Version(8, 0, 18))));
var app = builder.Build();

var accessToken = builder.Configuration.GetValue<string>("GiteeToken");
var requestUrl = builder.Configuration.GetValue<string>("GiteeUrls:orgrepos");
var connStr = builder.Configuration.GetConnectionString("leansoftxConnection");


var firstFlag=true;

app.MapGet("/leftdata/{key}", async(LeansoftContext db, string key) => {
    if(string.IsNullOrEmpty(key) && firstFlag)
        return Results.Problem("key不能为空！");
    key = System.Web.HttpUtility.UrlDecode(key??"");
    if (firstFlag)
    {
        using (var dbContextTransaction = db.Database.BeginTransaction())
        {
            db.tableLeft.RemoveRange(db.tableLeft);
            db.tableRight.RemoveRange(db.tableRight);
            db.SaveChanges();
            dbContextTransaction.Commit();
        }

        var allRepos = GetRepos(requestUrl,key,accessToken);
        db.tableLeft.AddRange(allRepos.Select(repo => new tableLeft { repoName = repo.name }));
        db.SaveChanges();
        firstFlag = false;  
    }
    var repos = db.tableLeft.Select(left=>left.repoName);
    return Results.Ok(repos);
});

app.MapGet("/rightdata", async(LeansoftContext db) => {
    var collectRepos =  db.tableRight.Select(right=>right.repoName);
    return Results.Ok(collectRepos);
});

app.MapGet("/collectrepo/{repo}", async(LeansoftContext db,string repo) => { 
    if(string.IsNullOrEmpty(repo))
        return Results.Problem("未提供仓库信息！");
    repo = System.Web.HttpUtility.UrlDecode(repo);
    int affectRows = 0;
    using (var dbContextTransaction = db.Database.BeginTransaction())
    {
        db.tableLeft.Remove(new tableLeft(){repoName = repo});
        db.tableRight.Add(new tableRight(){repoName = repo});
        affectRows = db.SaveChanges();
        dbContextTransaction.Commit();
    }
    return Results.Ok(affectRows> 0);
});

app.MapGet("/uncollectrepo/{repo}", async(LeansoftContext db,string repo) => { 
    if(string.IsNullOrEmpty(repo))
        return Results.Problem("未提供仓库信息！");
    repo = System.Web.HttpUtility.UrlDecode(repo);
    int affectRows = 0;
    using (var dbContextTransaction = db.Database.BeginTransaction())
    {
        db.tableLeft.Add(new tableLeft(){repoName = repo});
        db.tableRight.Remove(new tableRight(){repoName = repo});
        affectRows = db.SaveChanges();
        dbContextTransaction.Commit();
    }
    return Results.Ok(affectRows>0);
});

app.MapGet("/emailcontent/{key}", async(LeansoftContext db,string key) =>
{
    key = System.Web.HttpUtility.UrlDecode(key);
    var collectRepos = db.tableRight.Select(right => right.repoName).ToArray();
    var content = GetEmailContent(collectRepos,requestUrl,key,accessToken);
    return Results.Ok(content);
});

app.Run();


string GetEmailContent(string[] collectRepos,string requestUrl,string key,string accessToken)
{
    string format=@"{0}({1})";
    if(collectRepos.Length == 0) return "";

    var repoModels = GetRepos(requestUrl,key,accessToken);
    repoModels = repoModels.Where(model=>collectRepos.Contains(model.name.ToString())).ToArray();

    StringBuilder sBuilder=new StringBuilder("Hello,书蠡  这里是你收藏的代码库");
    sBuilder.AppendLine(""); sBuilder.AppendLine("");
    foreach(var repoModel in repoModels)
    {
        Console.WriteLine(String.Format(format,repoModel.name,repoModel.url,repoModel.description));
        sBuilder.AppendLine(String.Format(format,repoModel.name,repoModel.url));
        sBuilder.AppendLine(repoModel.description ??"");
        sBuilder.AppendLine("");
    }
    string content= sBuilder.ToString();
    return content;
}

repoModel[]  GetRepos(string requestUrl,string org,string accessToken)
{
    requestUrl =string.Format( requestUrl,org)+$"?access_token={accessToken}&type=all&page=1&per_page=100";
    HttpClient client = new HttpClient();
    var jsonStr =  client.GetStringAsync(requestUrl)?.Result;
     if(string.IsNullOrEmpty(jsonStr))
        return new repoModel[0];
     Console.WriteLine("调用Gitee接口成功！");
    return JsonConvert.DeserializeObject<repoModel[]>(jsonStr);
}






public class repoModel
{
    public string id { get; set; }
    public string name { get; set; }
    public string full_name { get; set; }
    public string url { get; set; }
    public string description { get; set; }
}

